const WebSocket = require('ws');

class WsService {

  async start(port, app) {
    try {
      app.room = new Set();
      const server = new WebSocket.Server({ port });

      console.log(`创建ws =====> ${port}`);
      server.on('connection', ws => {
        ws.on('message', message => {
          // const str = message.toString();
          if (message) {
            const info = JSON.parse(message.toString());

            if (info.action === 'register') {
              app.room.add(ws);
              ws.send(JSON.stringify({ action: 'register', msg: 'register is success' }));
            }
          }
        });

        ws.on('error', err => {
          console.log(err);
        });


        ws.on('close', () => {
          app.room.delete(ws);
        });
      });
    } catch (error) {
      throw error;
    }
  }
}


module.exports = new WsService();
